#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import sys
import requests
from io import BytesIO
from PIL import Image
import time
import random

# 添加项目路径到系统路径
project_path = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(project_path)

# 导入MinIO客户端
from backend.tools.minio_client import minio_client

def crawl_image(keyword):
    """
    从网络爬取图片
    :param keyword: 搜索关键词
    :return: 图片二进制数据
    """
    print(f"正在搜索图片: {keyword}")
    
    # 使用随机图片服务
    urls = [
        f"https://picsum.photos/600/300",  # 随机图片服务（轮播图尺寸）
        f"https://picsum.photos/200/200",  # 随机图片服务（头像/服务图片尺寸）
        f"https://picsum.photos/100/100",  # 随机图片服务（图标尺寸）
    ]
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    
    for url in urls:
        try:
            print(f"尝试从 {url} 获取图片...")
            response = requests.get(url, headers=headers, timeout=10)
            if response.status_code == 200:
                # 检查返回的内容是否是图片
                content_type = response.headers.get('content-type', '')
                if 'image' in content_type:
                    print(f"成功获取图片: {keyword}")
                    return response.content
                else:
                    print(f"URL返回的不是图片: {content_type}")
            else:
                print(f"请求失败，状态码: {response.status_code}")
        except Exception as e:
            print(f"获取图片失败: {e}")
            continue
        
        # 添加延迟避免被封
        time.sleep(random.uniform(1, 2))
    
    print(f"无法获取图片: {keyword}")
    return None

def resize_image(image_data, max_width, max_height):
    """
    调整图片大小
    :param image_data: 图片二进制数据
    :param max_width: 最大宽度
    :param max_height: 最大高度
    :return: 调整后的图片二进制数据
    """
    try:
        image = Image.open(BytesIO(image_data))
        
        # 如果图片尺寸超过限制，则调整大小
        if image.width > max_width or image.height > max_height:
            image.thumbnail((max_width, max_height), Image.Resampling.LANCZOS)
        
        # 转换为RGB模式（如果需要）
        if image.mode in ('RGBA', 'LA', 'P'):
            # 创建白色背景
            background = Image.new('RGB', image.size, (255, 255, 255))
            if image.mode == 'P':
                image = image.convert('RGBA')
            background.paste(image, mask=image.split()[-1] if image.mode in ('RGBA', 'LA') else None)
            image = background
        
        # 保存为JPEG格式
        output = BytesIO()
        image.save(output, format='JPEG', quality=85)
        return output.getvalue()
    except Exception as e:
        print(f"调整图片大小失败: {e}")
        return image_data  # 返回原始数据

def upload_to_minio(image_data, folder, filename):
    """
    上传图片到MinIO
    :param image_data: 图片二进制数据
    :param folder: 存储文件夹
    :param filename: 文件名
    :return: 图片URL
    """
    try:
        object_name = f"{folder}/{filename}"
        minio_client.upload_bytes(object_name, image_data, content_type="image/jpeg")
        url = minio_client.presigned_get_url(object_name)
        return url
    except Exception as e:
        print(f"上传图片到MinIO失败: {e}")
        return None

def main():
    """主函数"""
    print("开始爬取并上传项目所需图片...")
    
    # 项目需要的图片列表
    images_to_crawl = [
        # 轮播图
        {"name": "banner1", "keyword": "massage therapy", "folder": "banners", "width": 600, "height": 300, "format": "jpg"},
        {"name": "banner2", "keyword": "spa treatment", "folder": "banners", "width": 600, "height": 300, "format": "jpg"},
        
        # 分类图标
        {"name": "massage", "keyword": "massage icon", "folder": "icons", "width": 100, "height": 100, "format": "png"},
        {"name": "spa", "keyword": "spa icon", "folder": "icons", "width": 100, "height": 100, "format": "png"},
        {"name": "footcare", "keyword": "foot massage icon", "folder": "icons", "width": 100, "height": 100, "format": "png"},
        {"name": "bodycare", "keyword": "body care icon", "folder": "icons", "width": 100, "height": 100, "format": "png"},
        
        # 技师头像
        {"name": "technician1", "keyword": "massage therapist", "folder": "avatars", "width": 200, "height": 200, "format": "jpg"},
        {"name": "technician2", "keyword": "spa therapist", "folder": "avatars", "width": 200, "height": 200, "format": "jpg"},
        {"name": "technician3", "keyword": "beauty therapist", "folder": "avatars", "width": 200, "height": 200, "format": "jpg"},
        
        # 服务图片
        {"name": "service1", "keyword": "full body massage", "folder": "services", "width": 200, "height": 200, "format": "jpg"},
        {"name": "service2", "keyword": "foot massage", "folder": "services", "width": 200, "height": 200, "format": "jpg"},
    ]
    
    # 存储所有图片URL
    image_urls = {}
    
    for img_info in images_to_crawl:
        name = img_info["name"]
        keyword = img_info["keyword"]
        folder = img_info["folder"]
        width = img_info["width"]
        height = img_info["height"]
        format = img_info["format"]
        
        print(f"\n=== 爬取 {name} ===")
        
        # 爬取图片
        image_data = crawl_image(keyword)
        if image_data:
            # 调整大小
            resized_data = resize_image(image_data, width, height)
            # 上传到MinIO
            filename = f"{name}.{format}"
            url = upload_to_minio(resized_data, folder, filename)
            if url:
                image_urls[name] = url
                print(f"{name} 上传成功: {url}")
            else:
                print(f"{name} 上传失败")
        else:
            print(f"{name} 爬取失败")
        
        # 添加延迟
        time.sleep(random.uniform(1, 2))
    
    print("\n所有图片爬取和上传完成!")
    print("\n=== 图片URL汇总 ===")
    for name, url in image_urls.items():
        print(f"{name}: {url}")

if __name__ == "__main__":
    main()